package com.itxiuyixiu.service;

import com.itxiuyixiu.tools.sender.SimpleEmailService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author 黄磊
 * @date 2020/5/17
 */
@Service
public class EmailService {
    private final String prefix = "email:";
    private final SimpleEmailService emailService;
    private final ValueOperations<String, String> redisOperations;
    private final Random random = new Random();

    public EmailService(SimpleEmailService emailService, StringRedisTemplate stringRedisTemplate) {
        this.emailService = emailService;
        redisOperations = stringRedisTemplate.opsForValue();
    }

    public boolean sendVerification(@NonNull String email) {
        String verification = getVerification();
        if (!emailService.sendSimpleMail(email, "志愿者之家注册", "您的注册验证码："+verification+"\n请在15分钟内输入")) {
            return false;
        }
        redisOperations.set(prefix+email, verification, 15, TimeUnit.MINUTES);
        return true;
    }

    private String getVerification() {
        return String.format("%06d", random.nextInt(1000000));
    }
}
